<template>
    <el-upload class="avatar-uploader" list-type="picture-card" action="http://127.0.0.1:3007/user/avator"
        v-model:file-list="fileList" :headers="headers" :limit="limit" :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <el-icon class="avatar-uploader-icon">
            <Plus />
        </el-icon>
    </el-upload>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'


const props = defineProps({
    limit: {
        type: Number,
        default: 1
    }
})

const fileList = ref<UploadUserFile[]>([])
const headers = reactive({
    Authorization: localStorage.getItem("token")
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile,
    uploadFiles
) => {
    console.log("respose", response);
    console.log("uploadFile", uploadFile)
    console.log("uploadFiles", uploadFiles)
    console.log("fileList", fileList.value)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}
</script>
<style lang='scss' scoped>
// .avatar-uploader {
//     width: 120px;
//     height: 120px;
//     text-align: center;
//     line-height: 120px;
//     border: 1px dotted #d5d5d5;
// }</style>